package vn.bum.game.web;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.math.NumberUtils;

import vn.bum.game.api.GameDAO;
import vn.bum.game.web.base.ControllerServlet;
import vn.bum.game.web.base.Page;

public class GameServlet extends ControllerServlet {
	GameDAO gameDAO = new GameDAO();
	
	private String resolvePath(String folder) {
		return "game/" + folder;
	}

	@Override
	protected String getAction(HttpServletRequest req) {
		String action = "index";
		String info = req.getPathInfo();
		if (info != null && !"/".equals(info)) {
			if (info.startsWith("/"))
				info = info.substring(1);
			info = StringUtils.capitalize(info.split("/")[0]);
			if (!"Edit".equals(info)) {
				info = "Detail";
			}
			action = "game" + info;
		}
		return action;
	}

	public void indexAction(HttpServletRequest req, Page p) {
		int page = NumberUtils.toInt(req.getParameter("p"), 1);
		p.put("games", gameDAO.list(page));
		p.put("page", page);
		p.setTemplate(resolvePath("index"));
	}

	public void gameDetailAction(HttpServletRequest req, Page p) {
		String code = req.getPathInfo().substring(1);
		
		p.put("game", gameDAO.get(code));
		
		p.setTemplate(resolvePath("detail"));
	}
	
	public void gameEditAction(HttpServletRequest req, Page p) {
		if ("POST".equalsIgnoreCase(req.getMethod())) {
			long id = NumberUtils.toLong(req.getParameter("id"), 0);
			String title = req.getParameter("title");
			String code = req.getParameter("code");
			String intro = req.getParameter("intro");
			Long catId = NumberUtils.toLong(req.getParameter("catId"), 0);
			String jarUrl = req.getParameter("jarUrl");
			String jadUrl = req.getParameter("jadUrl");
			String content = req.getParameter("content");
			int fileSize = NumberUtils.toInt(req.getParameter("fileSize"), 0);
			String imageUrl = req.getParameter("imageUrl");
			
			if (id > 0) {
				gameDAO.update(id, title, code, intro, catId, jarUrl, jadUrl, content, fileSize, imageUrl);
			} else {
				gameDAO.create(title, code, intro, catId, jarUrl, jadUrl, content, fileSize, imageUrl);
			}
		}

		long id = NumberUtils.toLong(req.getParameter("id"), 0);
		if (id > 0) {
			p.put("game", gameDAO.get(id));
		}

		p.put("games", gameDAO.list());

		p.setTemplate(resolvePath("add"));
	}
}
